package app.service.loader
{
	
	import app.model.vo.AlertVO;
	import app.model.global.ApplicationModel;
	import app.view.helper.Alert;
	import app.view.event.AlertEvent;
	
	import com.gaiaframework.debug.GaiaDebug;
	
	import flash.events.*;
	import flash.net.*;
	import flash.utils.describeType;
	
	import org.robotlegs.mvcs.Actor;
	
	public class BaseURLLoaderService extends Actor implements URLLoaderServiceInterface
	{

		[Inject]
		public var appModel:ApplicationModel;
		
		protected var functionCalled:String;
		
		public function loadURL(url:String):void
		{
			var loader:URLLoader = new URLLoader();
			configureListeners(loader);
			
			var request:URLRequest = new URLRequest(url);
			try {
				loader.load(request);
			} catch (error:Error) {
				GaiaDebug.log("Unable to load requested document.");
			}
		}
		
		
		
		protected function configureListeners(disp:IEventDispatcher):void {
			disp.addEventListener(Event.COMPLETE, completeHandler);
			disp.addEventListener(Event.OPEN, openHandler);
			disp.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			disp.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			disp.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
			disp.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		}
		
		protected function completeHandler(event:Event):void {
			var loader:URLLoader = URLLoader(event.target);
			//GaiaDebug.log("BaseURLLoaderService completeHandler: " + loader.data);
			appModel.currentAlert = null;
			dispatch(new AlertEvent(AlertEvent.HIDE));
		}
		
		protected function openHandler(event:Event):void {
			GaiaDebug.log("BaseURLLoaderService openHandler: " + event);
			var vo:AlertVO = new AlertVO();
			vo.title = "CONNECTING";
			vo.message = "Connection with server established.";
			vo.type = Alert.SPINNER;
			appModel.currentAlert = vo;
			dispatch(new AlertEvent(AlertEvent.SHOW));
		}
		
		protected function progressHandler(event:ProgressEvent):void {
			//GaiaDebug.log("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
			//GaiaDebug.log("%: " + Math.round( (event.bytesLoaded/event.bytesTotal)*100) );
			var vo:AlertVO = new AlertVO();
			//vo.title = "LOADING";
			//vo.message = "Thank you for waiting while the information you need is retrieved.";// It is " + Math.round( (event.bytesLoaded/event.bytesTotal)*100) + "% complete.";
			vo.type = Alert.SPINNER;
			appModel.currentAlert = vo;
			dispatch(new AlertEvent(AlertEvent.SHOW));
		}
		
		protected function securityErrorHandler(event:SecurityErrorEvent):void {
			GaiaDebug.log("BaseURLLoaderService securityErrorHandler: " + event);
		}
		
		protected function httpStatusHandler(event:HTTPStatusEvent):void {
			GaiaDebug.log("BaseURLLoaderService httpStatusHandler: " + event);
		}
		
		protected function ioErrorHandler(event:IOErrorEvent):void {
			GaiaDebug.log("BaseURLLoaderService ioErrorHandler: " + event);
		}
	}
}